package com.ali.Reggie.service.impl;

import com.ali.Reggie.dto.DishDto;
import com.ali.Reggie.entity.Dish;
import com.ali.Reggie.entity.DishFlavor;
import com.ali.Reggie.mapper.DishMapper;
import com.ali.Reggie.service.DishFlavorService;
import com.ali.Reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ：ALi
 * @date ：Created in 2022/6/9 15:55
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    //保存两个张表的方法
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到数据库
        this.save(dishDto);
        //保存口味数据到口味表
            //获取菜品的id
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor:flavors) {
            flavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(flavors);


    }

    @Override
    public DishDto getByIDWithFlavor(Long id) {
        DishDto dishDto = new DishDto();

        //基本信息
        Dish dish = this.getById(id);

        //将基本信息复制到dishDto上
        BeanUtils.copyProperties(dish,dishDto);

        //查找口味表信息
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);

        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

    //修改后保存信息
    @Override
    @Transactional
    public void UpdateWithFlavorByID(DishDto dishDto) {
        //跟新菜品表
        this.updateById(dishDto);

        //更新口味表数据
            //  清理口味数据
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
            //  保存口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor:flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }
}